<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script>
        
        window.onerror = function(e){
            console.log('window.onerror:', e)
        }

        window.addEventListener('error', function(e){
            console.log('window.addEventListener error:', e)
        },true)


        function ajaxEventTrigger(event){
            // 自定义事件
            var ajaxEvent = new CustomEvent(event, {detail: this})
            // dispatchEvent 向一个指定的事件目标派发一个事件；向window派发一个指定的事件
            window.dispatchEvent(ajaxEvent)
        }

        var oldXHR = window.XMLHttpRequest;
        function newXHR(){
            var realXHR = new oldXHR()
            realXHR.addEventListener('loadstart', function(){
                ajaxEventTrigger.call(this, 'ajaxLoadStart')
            }, false)
            realXHR.addEventListener('loadend', function(){
                ajaxEventTrigger.call(this, 'ajaxLoadEnd')
            }, false)
            return realXHR
        }
        

        const timeRecordArray = []
        window.XMLHttpRequest = newXHR
        window.addEventListener('ajaxLoadStart', function(e){
            var tempObj = {
                timeStamp : new Date().getTime(),
                event: e,
                simpleUrl: window.location.href.split('?')[0].replace('#',''),
                uploadFlag: false // uploadFlag=true代表这个请求已经被上传过
            }
            timeRecordArray.push(tempObj)
        })
        

        window.addEventListener("ajaxLoadEnd", function(){
            // ajaxLoadEnd时会修改ajaxLoadStart产生的e，两者影响的是同一个对象e
            for (var i = 0; i < timeRecordArray.length; i ++) {
                if(timeRecordArray[i].uploadFlag === true) continue
                console.log("window.XMLHttpRequest addEventListener loadend: ", timeRecordArray[i].event.detail)
                timeRecordArray[i].uploadFlag  = true
            }
        })

    </script>
</head>
<body>
    
    <script src="./index.js"></script>
    <script src="./index2.js"></script>
</body>
</html>